Sample Scripts - Scrolling Text



Script #3. Simple scrolling text

This is probably one of the most annoying JavaScript's around. If you look at the browser's status bar (bottom left corner) you'll see a nice little message scrolling across it. This is done with JavaScript, like this :-

<SCRIPT LANGUAGE=JAVASCRIPT>

	myMsg = "whatever text you want to scroll goes here"
	i=0
	
	    
So here we have created a variable, myMsg, which contains a string. This string is the text which is going to scroll in the status bar. We set a new varable, i, which is going to act as a counter, and we initialiaze this with a value of 0. (a good place to start !)
Next we create a function called scrollMsg which is going to control the scrolling of the text.

	function scrollMsg()
	{
	frontPart = myMsg.substring(i,myMsg.length)
	backPart = myMsg.substring(0,i)
	window.status = frontPart + backPart
Here we have split the text into two parts, frontPart and backPart (good eh ?). To do this we use a JavaScript method called subString. Basically the two parts are measured by substring, the frontPart from the first letter onwards, the backPart from the last letter backwards, until the two meet. Here the string is cut in half. The whole process is controlled by our counter variable, i.
The next line tells the browser to display these in the status bar.

	if (i < myMsg.length)
	{
	    i++
	}
	else
	{
	    i = 0
	}
This is the crux of the script. Here we loop the program, increasing i each time, so long as i is less than the length of the message. When this is not the case, we reset i to 0. So, looking back at the substring method above, what this does in effect, is to assign a different part of the message to frontPart and backPart each time we loop. So, to explain :
	Imagine the message just said 'Hello'. The first time we run
	the program it splits this into two parts :-
	
		frontPart = Hel
		backPart  = lo

	On the next loop these would be :-

		frontPart = oHe
		backPart  = ll
	
	(the whole message has just shifted one space to the right)

	This 'shift to the right' is controlled by the variable i.
The final part of the script controls the scrolling speed.

	setTimeout("scrollMsg()",50)
}
The setTimeout method is JavaScripts way of pausing a function. We simply pass the name of the function to it in parentheses and add a time period in milliseconds for the length of the pause. ("scrollMsg()",50)
And that's that. Simple huh !!!


<< BACK - HOME - - RESOURCES - NEXT EXAMPLE >>